# language: JSVM2

/**
 * @author:	Wan Changhua
 * @date:	2005.08.03.01
 */

package com.homolo.commons.codec;

import js.lang.System;
import js.lang.StringBuffer;
import js.lang.NotSupportException;

import com.homolo.commons.codec.GB2312Codec;

class StringCodec ()
{
	/* Don't let anyone instantiate this class
	 */
	throw new NotSupportException(StringCodec.getName()
		+ " cannot be instantiated.");
}

var hexes = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];

StringCodec.strToHex = function (s)
{
	var sb = new StringBuffer();
	for (var i = 0; i < s.length; i++)
	{
		var c = s.charCodeAt(i);
		if (c > 0xff)
		{
			sb.append(GB2312Codec.encode(s.charAt(i)));
			/** blank out
			var c0 = c >> 8;
			var c1 = c & 0xff;
			sb.append(hexes [c0 >> 4])
			sb.append(hexes [c0 & 0xf]);
			sb.append(hexes [c1 >> 4])
			sb.append(hexes [c1 & 0xf]);
			*/
		}
		else
		{
			sb.append(hexes [c >> 4])
			sb.append(hexes [c & 0xf]);
		}
	}
	return sb.toString();
}

StringCodec.hexToStr = function(s)
{
	var sb = new StringBuffer();
	for (var i = 0; i < s.length; i++)
	{
		var c = parseInt(s.charAt(i) + s.charAt(i + 1), 16);
		if (c > 0x80)
		{
			sb.append(GB2312Codec.encode(s.substring(i, i + 4)));
			i += 3;
			/** blank out
			var c0 = c >> 8;
			var c1 = c & 0xff;
			sb.append(hexes [c0 >> 4])
			sb.append(hexes [c0 & 0xf]);
			sb.append(hexes [c1 >> 4])
			sb.append(hexes [c1 & 0xf]);
			*/
		}
		else
		{
			sb.append(String.fromCharCode(c));
			i++;
		}
	}
	return sb.toString();
}

